import React, { useEffect, useMemo, useState } from "react";
import { Modal, Form, Input, Row, Col, Radio, DatePicker, Steps, Space } from "antd";
import { cabinetTypes, modalPropsType } from "@/constants/types";
import { cabinetNodeMaps} from "@/constants/dictData";
import { fetchBookingDetail } from "../../services";
import dayjs from "dayjs";

const {Item} = Form;
const labelCol = {span: 7};

const CabinetTrackPart = ({tracks}: {tracks: any []}) => {
  const current = tracks?.findIndex((v: any) => v.flag === 0);

  return (
    <div style={{marginTop: 30, padding: 20, backgroundColor: '#f5f5f5', borderRadius: '10px'}}>
      <Steps
        progressDot
        current={current - 1}
        items={tracks?.map((v: any) => ({
          title: v?.nodeName,
          description: v?.nodeTime
        }))}
      />
    </div>
  );
}

const TrackMarking = ({visible, onCancel, onSubmit, title, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const node = currentRow?.node;

  // 获取下一个节点进行打标，如果当前节点的下个节点可能为多个则需要增加一个shipNode来处理
  const nextNodes = cabinetNodeMaps.find((v: any) => v.value === node)?.next;
  const isMultipleNode = nextNodes?.length > 1;
  const shipNode = Form.useWatch('shipNode', form);

  const [detail, setDetail] = useState<cabinetTypes>({});

  const fetchDetail = async (id: string) => {
    const res = await fetchBookingDetail({id});
    setDetail(res || {});
  }


  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      id: currentRow?.id,
      bookingStatus: res?.bookingStatus,
      businessTime: res?.businessTime ? res.businessTime?.format('YYYY-MM-DD HH:mm:ss') : ''
    });
  }

  const statusList = useMemo(() => {
    if (!currentRow || !shipNode) {
      return [];
    }
    console.log("aaa", shipNode, isMultipleNode, JSON.stringify(cabinetNodeMaps), JSON.stringify(currentRow), JSON.stringify(nextNodes));
    const obj = {};
    nextNodes.forEach(currNode => {
      const maps = cabinetNodeMaps.find(v => v.value === currNode?.value)?.statusMaps || [];
      obj[currNode?.value] = maps;
    })
    return obj;
  }, [shipNode, isMultipleNode, JSON.stringify(cabinetNodeMaps), JSON.stringify(currentRow), JSON.stringify(nextNodes)]);

  useEffect(() => {
    if (currentRow) {
      form.setFieldsValue({
        shipNode: isMultipleNode ? undefined : nextNodes?.[0]?.value,
        cabinetCode: currentRow?.cabinetCode,
        so: currentRow?.so
      });
    }
  }, [isMultipleNode, JSON.stringify(currentRow)]);


  useEffect(() => {
    if (currentRow?.id) {
      fetchDetail(currentRow?.id);
    }
  }, [JSON.stringify(currentRow)])

  return (
    <Modal
      title={title}
      confirmLoading={loading}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      width="1200px"
      maskClosable={false}
    >
      <CabinetTrackPart tracks={detail?.tracks || []} />
      <Form form={form} labelCol={labelCol} className="modal-form-padding">
        <Row>
          <Col span={12}>
            <Item label="柜号/虚拟柜号" name="cabinetCode">
              <Input disabled />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="SO" name="so">
              <Input disabled />
            </Item>
          </Col>
        </Row>
        {
          isMultipleNode ? (
            <Row>
              <Col span={12}>
                <Item label="节点" name="shipNode">
                  <Radio.Group
                    options={nextNodes}
                  />
                </Item>
              </Col>
            </Row>
          ) : (
            <Item noStyle hidden name="shipNode">
              <Input />
            </Item>
          )
        }
        <Row>
          <Col span={12}>
            <Item label="轨迹" name="bookingStatus" rules={[{required: true}]}>
              <Radio.Group
                options={statusList?.[shipNode] || []}
              />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="业务时间" name="businessTime" rules={[{required: true}]}>
              <DatePicker style={{width: 336}} />
            </Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}
export default TrackMarking;